package com.bigdatastudio.monitor.Aop;

import com.bigdatastudio.common.Utils.R;
import com.bigdatastudio.common.dto.NoticeParm;
import com.bigdatastudio.common.entity.Notice;
import com.bigdatastudio.monitor.SearchVo.SearchNoticeVo;
import com.bigdatastudio.notice.server.INoticeService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xiao_jie
 * @date 2022/11/8 20:12
 * @describe 设置切入点，每次公告数据更新都会让elasticsearch里面的数据更新
 */

@Component
@Aspect
@Slf4j
public class NoticeAop {

    @Autowired
    private INoticeService service;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Pointcut("execution(public * com.bigdatastudio.*.controller.*.addorupdate(..))")
    public void NoticeAopCut() {
    }

    @Before(value = "NoticeAopCut()")
    public void NoticeBefore() {
        IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(SearchNoticeVo.class);
        boolean exists = indexOperations.exists();
        if (exists){
            return;
        }
        else {
            indexOperations.create();
            Document mapping = indexOperations.createMapping(SearchNoticeVo.class);
            indexOperations.putMapping(mapping);
        }
        List<Notice> list = service.list();
        for (Notice n:
             list) {
            SearchNoticeVo vo = new SearchNoticeVo();
            BeanUtils.copyProperties(n,vo);
            elasticsearchRestTemplate.save(vo);
        }
        log.info("正在将Notice表内的全部数据导入elasticsearch");
    }

    @AfterReturning(value = "NoticeAopCut()")
    public void StarAfter(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        NoticeParm parm = (NoticeParm) args[0];
        Notice notice = service.getById(parm.getId());
        SearchNoticeVo vo = new SearchNoticeVo();
        BeanUtils.copyProperties(notice,vo);
        elasticsearchRestTemplate.save(vo);
        log.info("notice更新的数据已经成功导入elasticsearch");
    }

}
